package com.fingard.dsp.bank.directbank.lzccb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author Alon on 2019-10-11.
 * @version 1.0
 */
public class LZCCB01Base extends DirectBase implements ITcpClient {

    protected static TransIDHelper idHelper = new TransIDHelper(1, 9999);

    private String separator = "|";

    public Map<String, Object> writerPayFileContext(ReqBatPayRec p_req1988) throws Exception {
        //凭证类型|凭证号（流水号）|收款账号|收款币种|收款户名|收款地址|金额|账簿标志|付款账簿号|付款账簿名|
        // 收款行号|收款行名|跨行标志|同城异地|加急标志|用途|附言|预约标志|预约日期|预约时间|
        // 收款方手机号码|是否保存收款方信息|
        Map<String, Object> resultAndfileContext = new HashMap<String, Object>();
        StringBuilder msgXml = new StringBuilder();
        msgXml.append("CERT_TYPE|CERT_NO|RCV_ACNO|RCV_CUR_CODE|RCV_ACNAME|RCV_ACCADDR|AMT|AS_FLAG|AS_ACNO|AS_ACNAME|RCV_BANK_NO|RCV_BANK_NAME|BANK_FLAG|AREA_FLAG|URGENCY_FLAG|PURPOSE|POSTSCRIPT|BOOKING_FLAG|BOOKING_DATE|BOOKING_TIME|MOBILES|SAVERECVINFO_FLAG|");
        msgXml.append("\r\n");
        int tmpCount = 0;
        while (p_req1988.readRecord()) {
            tmpCount++;
            msgXml.append("流水号").append(separator);//凭证类型（流水号）
            msgXml.append(p_req1988.readedDetail.askNumber).append(separator);//每笔的批次内流水号
            msgXml.append(p_req1988.readedDetail.recAct).append(separator);//收款账号
            msgXml.append(convertCurToBank(p_req1988.readedDetail.recCur)).append(separator);//收款币种
            msgXml.append(p_req1988.readedDetail.recName).append(separator);//收款户名
            msgXml.append(p_req1988.readedDetail.recAreaName).append(separator);//收款地址
            msgXml.append(p_req1988.readedDetail.payAmount).append(separator);//交易金额
            msgXml.append("0").append(separator);//账簿标志
            msgXml.append(separator);//付款账簿号
            msgXml.append(separator);//付款账簿名
            msgXml.append(p_req1988.readedDetail.cnapsCode).append(separator);//收款行号
            msgXml.append(p_req1988.readedDetail.cnapsName).append(separator);//收款行名
            msgXml.append(p_req1988.readedDetail.sameBnk).append(separator);//跨行标志
            msgXml.append(p_req1988.readedDetail.sameCity).append(separator);//同城异地
            msgXml.append(p_req1988.readedDetail.paySpd).append(separator);//加急标志
            msgXml.append(p_req1988.readedDetail.memo).append(separator);//用途(ATS用途字段读取为空，将用途写在备注里)
            msgXml.append(p_req1988.readedDetail.abstractATS).append(separator);//附言(对账码)
            msgXml.append("0").append(separator);//预约标志??
            msgXml.append(separator);//预约日期??
            msgXml.append(separator);//预约时间??
            msgXml.append(separator);//收款方手机号码??
            msgXml.append(separator);//是否保存收款方信息??
            msgXml.append("\r\n");
        }
        if (tmpCount != Integer.parseInt(p_req1988.totalNum)) {
            resultAndfileContext.put("result", "false");
        } else {
            resultAndfileContext.put("result", "true");
        }
        resultAndfileContext.put("fileContext", msgXml);
        return resultAndfileContext;
    }

    protected void writeCommonHeader(XmlTextWriter xmlWriter, LZCCB01Header p_bankHeader) throws Exception {
        xmlWriter.writeStartElement("ap");
        xmlWriter.writeStartElement("head");
        xmlWriter.writeElementString("tr_code", p_bankHeader.trCode, true);
        xmlWriter.writeElementString("cms_corp_no", bankFront.corpNo, true);//m:企业不需要赋企，由银企前置机进行赋值。
        xmlWriter.writeElementString("user_no", "", true);//m:企业不需要赋企，由银企前置机进行赋值。
        xmlWriter.writeElementString("org_code", "", true);//m:企业不需要赋企，由银企前置机进行赋值。
        xmlWriter.writeElementClosed("serial_no");//c:由银企直联系统产生（交易流水号）
        xmlWriter.writeElementString("req_no", p_bankHeader.reqNo, true);//企业erp的流水号(流水号)
        Date date = new Date();
        xmlWriter.writeElementString("tr_acdt", Format.Date8Format.format(date));
        xmlWriter.writeElementString("tr_time", Format.Time6Format.format(date));
        xmlWriter.writeElementString("channel", "5");//erp送‘5’
        xmlWriter.writeElementString("sign", "1");
        xmlWriter.writeElementString("file_flag", p_bankHeader.fileFlag);//0-报文1-文件
        xmlWriter.writeElementString("reserved", "", true);
        xmlWriter.writeEndElement();
    }

    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    /**
     * 发送银行前置
     *
     * @param p_reqStr
     * @return
     * @throws Exception
     */
    protected String[] sendToBank(String p_reqStr) throws Exception {
        byte[] tmpBytes = p_reqStr.getBytes(getCharset());
        int XMLlength = tmpBytes.length + 2;
        StringBuilder reqContext = new StringBuilder(p_reqStr).insert(0, String.format("%010d", XMLlength) + "00");
        //发送银行前置
        String[] retStr = new String[]{"", ""};
        WriteBankUrlLogLn("请求银行的地址" + bankFront.serverIP + ":" + bankFront.serverPort);
        WriteBankLogStep2(reqContext.toString());
        //发送银行前置
        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
        tmpClient.timeoutMil = 300000;
        TcpReceiver tmpReceiver = tmpClient.sendMessage(reqContext.toString(), getCharset());
        retStr[0] = tmpReceiver.connState;
        retStr[1] = tmpReceiver.getFullString(getCharset());
        if(StringHelper.isNullOrEmpty(retStr[1])){
        	retStr[1] = tmpReceiver.getConnMsg();
        }else{
        	retStr[1] = tmpReceiver.getFullString(getCharset());
        	int idx = retStr[1].indexOf("<ap>");
        	if(idx != -1){
        		retStr[1] = retStr[1].substring(idx);
        	}
        }
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }

    @Override
    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            String tmpCharset = getCharset();
            String tmpRecNow = new String(p_receiver.recBytes, 0, p_receiver.readedLength, tmpCharset);
            if (tmpRecNow.contains("</ap>")) {
                p_receiver.contentLength = p_receiver.readedLength;
                p_receiver.contentStartIndex = 0;
            }
        }
    }
}
